package com.dlz.systemshop.service.impl;

import com.dlz.systemshop.mapper.GoodsAlbumMapper;
import com.dlz.systemshop.pojo.GoodsAlbum;
import com.dlz.systemshop.service.GoodsAlbumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Stream;

@Service
public class GoodsAlbumServiceImpl implements GoodsAlbumService {

    @Autowired
    private GoodsAlbumMapper goodsAlbumMapper;

    @Override
    @Transactional
    public Boolean savePicList(List<GoodsAlbum> goodsAlbums, Integer id) {

        // 获取原来的
        List<GoodsAlbum> oldList = goodsAlbumMapper.getList(id);
        HashSet<Integer> newIds = getIds(goodsAlbums);
        // 过滤出要删除的id
        List<Integer> delIds = lack(newIds, oldList);
        // 获取要添加的内容
        List<GoodsAlbum> addList = goodsAlbums.stream().filter((item) -> item.getId() == null).toList();
        Integer delNums = 0, addNums = 0;
        // 不能为空
        if (!delIds.isEmpty()) {
            delNums = goodsAlbumMapper.delList(delIds);
        }
        if (!addList.isEmpty()) {
            addNums = goodsAlbumMapper.insertList(addList);
        }
        return delNums > 0 || addNums > 0;
    }

    // 不需要处理了 因为图片只有被添加和删除 而添加是一定没有 http 开头的
    private void dealGoodsAlbumsUrl(List<GoodsAlbum> goodsAlbums) {

    }

    @Override
    public List<GoodsAlbum> getListByGoodsId(Integer goodsId) {
        return goodsAlbumMapper.getList(goodsId);
    }

    // 第一个比第二个少哪些 id
    private List<Integer> lack(HashSet<Integer> ids1, List<GoodsAlbum> ids2) {
        List<Integer> ret = new LinkedList<>();
        for (GoodsAlbum id2 : ids2) {
            if (!ids1.contains(id2.getId())) {
                ret.add(id2.getId());
            }
        }
        return ret;
    }

    // 获取 id
    private HashSet<Integer> getIds(List<GoodsAlbum> list) {
        HashSet<Integer> set = new HashSet<>(list.size());
        for (GoodsAlbum goodsAlbum : list) {
            set.add(goodsAlbum.getId());
        }
        return set;
    }
}
